package com.zsh.jedis;

import redis.clients.jedis.Jedis;

import java.util.Random;

/**
 * @author zsh
 * @Description
 * @create 2022-04-21 10:38
 */
public class PhoneCode {
    public static void main(String[] args) {
        //模拟验证码发送
        //verifyCode("138300200221");
        getRedisCode("138300200221","172896");

    }

    //1.生成6位数字
    public static String getCode(){
        Random random = new Random();
        String code = "";
        for (int i = 0;i<6;i++){
            int rand = random.nextInt(10);
            code += rand;
        }
        return code;
    }

    //2.每个手机每天发送三次，验证码放redis中，设置过期时间
    public static void verifyCode(String phone){
        //链接redis
        Jedis jedis = new Jedis("192.168.200.128",6379);

        //拼接key
        String countKey = "VerifyPhone" + phone + ":count";
        String codeKey = "VerifyCode" + phone + ":code";

        String count = jedis.get(countKey);

        if (count == null){
            //第一次发送
            //设置发送次数为1
            jedis.setex(countKey,24*60*60,"1");
        }else if (Integer.parseInt(count) <= 2){
            //发送次数+1
            jedis.incr(countKey);
        } else if (Integer.parseInt(count) > 2){
            //不能发送了
            System.out.println("今天发送次数超过三次");
            jedis.close();
            return;
        }

        //发送的验证码，放入redis
        String vcode = getCode();
        jedis.setex(codeKey,120,vcode);
        jedis.close();
    }

    //3.验证码校验
    public static void getRedisCode(String phone, String code){
        //从redis中获取
        Jedis jedis = new Jedis("192.168.200.128",6379);
        String codeKey = "VerifyCode" + phone + ":code";

        String redisCode = jedis.get(codeKey);
        if (redisCode.equals(code)){
            System.out.println("成功");
        } else {
            System.out.println("失败");
        }

        jedis.close();
    }
}
